<template>
  <div class="comment-tree-node" :class="{ 'has-children': hasChildren }">
    <div class="node-content" :style="{ paddingLeft: `${(level - 1) * 20}px` }">
      <div class="node-header">
        <div class="expand-button">
          <el-button
            v-if="hasChildren"
            :icon="expanded ? 'ArrowDown' : 'ArrowRight'"
            size="small"
            text
            @click="handleToggleExpand"
          />
          <span v-else class="no-expand-placeholder" />
        </div>

        <div class="user-info">
          <el-avatar
            :src="formatAvatarUrl(comment.userAvatar)"
            :size="32"
            fit="cover"
          >
            <template #default>
              <IconifyIconOnline icon="ep:user" />
            </template>
          </el-avatar>
          <div class="user-details">
            <div class="user-name">
              {{ comment.userNickName || comment.userName }}
            </div>
            <div class="comment-meta">
              <span class="level-badge">L{{ comment.level }}</span>
              <span class="time">{{ formatTime(comment.createTime) }}</span>
              <el-tag :type="getStatusTagType(comment.status)" size="small">
                {{ getStatusText(comment.status) }}
              </el-tag>
              <el-tag
                v-if="CommentManagementUtils.toBool(comment.isSensitive)"
                type="danger"
                size="small"
              >
                敏感
              </el-tag>
            </div>
          </div>
        </div>

        <div class="node-actions">
          <el-button
            v-if="comment.status === 0"
            type="success"
            size="small"
            @click="handleAudit(1)"
          >
            通过
          </el-button>
          <el-button
            v-if="comment.status === 0"
            type="danger"
            size="small"
            @click="handleAudit(2)"
          >
            拒绝
          </el-button>
          <el-dropdown @command="handleDropdownCommand">
            <el-button size="small">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="detail">查看详情</el-dropdown-item>
                <el-dropdown-item command="ban">禁言用户</el-dropdown-item>
                <el-dropdown-item command="delete" divided
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <div class="node-body">
        <div class="comment-content">
          <p>{{ comment.content }}</p>
          <div class="interaction-data">
            <span class="like-count">👍 {{ comment.likeCount }}</span>
            <span class="reply-count">💬 {{ comment.replyCount }}</span>
            <span class="ip-info">IP: {{ comment.ipAddress }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 子评论 -->
    <div v-if="hasChildren && expanded" class="children-nodes">
      <CommentTreeNode
        v-for="child in comment.children"
        :key="child.id"
        :comment="child"
        :level="level + 1"
        :expanded="childExpandedStates[child.id] || false"
        @toggle-expand="handleChildToggleExpand"
        @view-detail="$emit('view-detail', $event)"
        @audit="$emit('audit', $event, $event)"
        @delete="$emit('delete', $event)"
        @ban-user="$emit('ban-user', $event)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive } from "vue";
import { ArrowDown, ArrowRight } from "@element-plus/icons-vue";
import { IconifyIconOnline } from "@/components/ReIcon";
import {
  type CommentInfo,
  CommentManagementUtils
} from "@/api/comment-management";

// Props
interface Props {
  comment: CommentInfo;
  level: number;
  expanded: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  level: 1,
  expanded: false
});

// Emits
const emit = defineEmits<{
  "toggle-expand": [commentId: number];
  "view-detail": [comment: CommentInfo];
  audit: [comment: CommentInfo, auditResult: 1 | 2];
  delete: [comment: CommentInfo];
  "ban-user": [comment: CommentInfo];
}>();

// 响应式数据
const childExpandedStates = reactive<Record<number, boolean>>({});

// 计算属性
const hasChildren = computed(() => {
  return props.comment.children && props.comment.children.length > 0;
});

// 方法
const handleToggleExpand = () => {
  emit("toggle-expand", props.comment.id);
};

const handleChildToggleExpand = (commentId: number) => {
  childExpandedStates[commentId] = !childExpandedStates[commentId];
};

const handleAudit = (auditResult: 1 | 2) => {
  emit("audit", props.comment, auditResult);
};

const handleDropdownCommand = (command: string) => {
  switch (command) {
    case "detail":
      emit("view-detail", props.comment);
      break;
    case "ban":
      emit("ban-user", props.comment);
      break;
    case "delete":
      emit("delete", props.comment);
      break;
  }
};

// 工具方法
const getStatusText = (status: number) => {
  return CommentManagementUtils.getStatusText(status);
};

const getStatusTagType = (status: number) => {
  return CommentManagementUtils.getStatusTagType(status);
};

const formatTime = (time: string) => {
  return CommentManagementUtils.formatTime(time);
};

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};
</script>

<style scoped lang="scss">
.comment-tree-node {
  margin-bottom: 8px;

  &.has-children {
    .node-content {
      border-left: 2px solid #e4e7ed;
    }
  }

  .node-content {
    padding: 12px;
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 8px rgb(64 158 255 / 10%);
    }

    .node-header {
      display: flex;
      gap: 8px;
      align-items: flex-start;
      margin-bottom: 8px;

      .expand-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;

        .no-expand-placeholder {
          width: 16px;
          height: 16px;
        }
      }

      .user-info {
        display: flex;
        flex: 1;
        gap: 12px;
        align-items: center;

        .user-details {
          .user-name {
            margin-bottom: 4px;
            font-weight: 500;
            color: #303133;
          }

          .comment-meta {
            display: flex;
            gap: 8px;
            align-items: center;
            font-size: 12px;

            .level-badge {
              padding: 2px 6px;
              font-weight: 500;
              color: #606266;
              background: #f0f2f5;
              border-radius: 4px;
            }

            .time {
              color: #909399;
            }
          }
        }
      }

      .node-actions {
        display: flex;
        gap: 8px;
        align-items: center;
      }
    }

    .node-body {
      margin-left: 32px;

      .comment-content {
        p {
          margin: 0 0 8px;
          line-height: 1.6;
          color: #303133;
          word-break: break-word;
        }

        .interaction-data {
          display: flex;
          gap: 16px;
          align-items: center;
          font-size: 12px;
          color: #909399;

          .like-count,
          .reply-count {
            display: flex;
            gap: 4px;
            align-items: center;
          }

          .ip-info {
            font-family: monospace;
          }
        }
      }
    }
  }

  .children-nodes {
    position: relative;
    padding-left: 16px;
    margin-top: 8px;
    margin-left: 20px;
    border-left: 2px solid #f0f0f0;

    &::before {
      position: absolute;
      top: 0;
      bottom: 0;
      left: -2px;
      width: 2px;
      content: "";
      background: linear-gradient(to bottom, #409eff, transparent);
    }
  }

  // 不同层级的样式
  &[data-level="1"] .node-content {
    border-left-color: #409eff;
    border-left-width: 3px;
  }

  &[data-level="2"] .node-content {
    border-left-color: #67c23a;
    border-left-width: 3px;
  }

  &[data-level="3"] .node-content {
    border-left-color: #e6a23c;
    border-left-width: 3px;
  }

  &[data-level="4"] .node-content {
    border-left-color: #f56c6c;
    border-left-width: 3px;
  }
}

// 将层级样式合并到主选择器中，避免重复选择器警告
</style>
